﻿/*-----------------------------------------------------------------------
 * <copyright file="AccountManagementControl.xaml.cs" company="O-RID">
 *     Copyright (c)2010 O-RID Co.,Ltd.
 * </copyright>
 * <author>Zhang jun</author>
 * <summary>
 *          登录帐号管理
 *      引用服务：WCFServers.WCFAccountsRef 
 *      服务功能：数据的增加，查询，删除
 *     
 *      引用服务：WCFLog4Ref.WCFLog4Client
 *      服务功能：记录日志
 *      
 *      作成日：05/21/2010
 *              09/20/2010 增加 增加新用户按钮
 * </summary>
 *----------------------------------------------------------------------- 
 */

namespace Orid.Management.Statistics.OperatorUnitMangement.CompetenceSetPaeg.AccountManagement
{
    using System;
    using System.Collections.ObjectModel;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Media;
    using Orid.Management.Statistics.OperatorUnitMangement.Common.FunctionList;
    using Orid.Management.Statistics.OperatorUnitMangement.WCFLog4Ref;
    using Orid.Management.Statistics.OperatorUnitMangement.WCFServers.WCFAccountsRef;
    using childWindow = Orid.Management.Statistics.OperatorUnitMangement.Common.Window;
    using Wcf = Orid.Management.Statistics.OperatorUnitMangement.Common.Service;
    using System.Collections.Generic;

    /// <summary>
    /// 帐号管理页面
    /// AccountManagementControl
    /// </summary>
    public partial class AccountManagementControl : UserControl
    {
        #region 全局变量

        /// <summary>
        /// 当前应用对象
        /// Application.Current
        /// </summary>
        private App app = (App)Application.Current;

        /// <summary>
        /// 消息子窗口
        /// deleteMessbox
        /// </summary>
        private childWindow.MessageBox deleteMessbox;

        /// <summary>
        /// 错误提示子窗口
        /// errorMessbox
        /// </summary>
        private childWindow.MessageBox errorMessbox;

        /// <summary>
        /// 分页控件
        /// PagedCollectionView
        /// </summary>
        private PagedCollectionView pcv;

        /// <summary>
        /// Grid 页面行数
        /// pageCount
        /// </summary>
        private int pageCount = 100;
           
        /// <summary>
        /// ObservableCollection当数据增加或册除时，同时更新。
        /// 为dagagrid的checkbox增加了一个CHECK状态字段
        /// </summary>
        private ObservableCollection<Client_AccountManagementDataList> clientList;
        /// <summary>
        /// 服务定义
        /// WCFAccountsClient
        /// </summary>
        private WCFAccountsClient client;
    
        /// <summary>
        /// 日志服务定义
        /// WCFLog4Client
        /// </summary>
        private WCFLog4Client wcfLogClient;
        
        /// <summary>
        /// 数据子窗口
        /// amlsc
        /// </summary>
        private AccountManagementListShowChild amlsc;

        #endregion  全局变量
        
        /// <summary>
        /// 构造函数
        /// AccountManagementControl
        /// </summary>
        public AccountManagementControl()
        {
            InitializeComponent();
            
            // 引用主题
            ((App)Application.Current).SetTheme(this);

            this.dgAccountManagement.HeadersVisibility = DataGridHeadersVisibility.All;//同时显示DataGrid的行头与列头

            Initialize();

            ////服务地址的绑定
            ////EndpointAddress address = new EndpointAddress(new Uri(Application.Current.Host.Source, app.strURI));
            ////client = new Orid.Management.Statistics.OperatorUnitMangement.WCFDecomposition.AccountsRef.WCFAccountsClient(new BasicHttpBinding(), address);
            
            // 为dgAccountManagement定义的服务
            this.client.AccountManagementCompleted += new EventHandler<WCFServers.WCFAccountsRef.AccountManagementCompletedEventArgs>(this.Client_AccountManagementCompleted);

            // 增加记录  的服务委托
            this.client.InsertAccountCompleted += new EventHandler<InsertAccountCompletedEventArgs>(this.Client_InsertAccountCompleted);

            // 删除记录  的服务委托
            this.client.DeleteAccountCompleted += new EventHandler<DeleteAccountCompletedEventArgs>(this.Client_DeleteAccountCompleted);

            // 自定义页面载入事件
            this.Loaded += new RoutedEventHandler(this.Page_Loaded);

            // 数据字窗口关闭事件
            this.amlsc.Closed += new EventHandler(this.Amlsc_Closed);

            // 消息子窗口关闭事件
            this.deleteMessbox.Closed += new EventHandler(this.DeleteMessbox_Closed);
            
            //添加用户
            this.AppendNew.Click += new RoutedEventHandler(AppendNew_Click);

          
        }

        
        private void Initialize()
        {
            this.wcfLogClient = Wcf.Service.Log4;

            this.client = Wcf.Service.Accounts;

            this.clientList = new ObservableCollection<Client_AccountManagementDataList>();

            this.amlsc = new AccountManagementListShowChild();

            this.deleteMessbox = new childWindow.MessageBox();

            this.errorMessbox = new childWindow.MessageBox();

        }

        #region 增加新用户 按钮

        /// <summary>
        /// 增加新用户 按钮
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The  instance containing the event data.</param>
        void AppendNew_Click(object sender, RoutedEventArgs e)
        {
            AddNewAccountChild addNewChild = new AddNewAccountChild();
            addNewChild.Show();
        }

        #endregion 增加新用户 按钮


        #region 增加记录

        /// <summary>
        /// 添加已有用户 按钮
        /// Append_Click
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of RoutedEventArgs</param>
        private void Append_Click(object sender, RoutedEventArgs e)
        {
            ClientDataList.ParameterAccountList.Clear();

            // 显示子窗体
            this.amlsc.Show();

            // 清空子窗体上的TEXT控件
            this.amlsc.tbInput.Text = String.Empty;
            this.amlsc.tbInput.Text = "搜索用户名";
        }

        /// <summary>
        /// 数据子窗体关闭事件
        /// (增加记录)
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of EventArgs</param>
        private void Amlsc_Closed(object sender, EventArgs e)
        {
            try
            {
                if (ClientDataList.ParameterAccountList.Count <= 0)
                {
                    return;
                }

                // 当确定增加时
                this.amlsc = sender as AccountManagementListShowChild;

                if (amlsc == null) { return; }

                if (this.amlsc.DialogResult == true && ClientDataList.ParameterAccountList.Count > 0)
                {
                    /// 11/17/2010 EDIT   
                    /// 遍历ParameterAccountList列表，判断新记录的用户名是否存在
                    /// 如果存在，把存在的记录合成 列表 isHave
                    /// 如果不存在，把不存在的记录合成 列表 isNoHave
                    ObservableCollection<string> isHave = new ObservableCollection<string>();
                    ObservableCollection<string> isNoHave = new ObservableCollection<string> ();

                    //没有重值
                    List<string> newParameterAccountList = new List<string>();

                    //把添加重复人的去除
                    foreach (string str in ClientDataList.ParameterAccountList)
                    {
                        string[] strList = str.Split(',');
                        bool isSame = false;
                        foreach (Client_AccountManagementDataList accountManagement in this.clientList) 
                        {
                            if (accountManagement.AccountID.Equals(strList[0], StringComparison.OrdinalIgnoreCase))
                            {
                                isSame = true;
                            }
                            else 
                            {
                                continue;
                            }
                        }
                        //如果 没在重复值 
                        if (!isSame) 
                        {
                            newParameterAccountList.Add(str);
                        }
                    }

                    if (newParameterAccountList.Count <= 0) { return; }
                   
                    foreach (string str in newParameterAccountList) 
                    {
                        string[] strList = str.Split(',');
                        
                        // SVInfo里不存在 用户名
                        if (strList[1].Equals("Unkonw", StringComparison.OrdinalIgnoreCase))
                        {
                            isNoHave.Add(strList[0].Trim());
                        }
                        // SVInfo里存在 用户名
                        else 
                        {
                            isHave.Add(strList[0].Trim());
                        }
                    }

                    // 插入新值(服务)
                    this.client.InsertAccountAsync(isHave, isNoHave);

                    ClientDataList.ParameterAccountList.Clear();
                }

                if (this.amlsc.DialogResult == false)
                {
                    ClientDataList.ParameterAccountList.Clear();
                }
            }
            catch (Exception ex) 
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + "AccountManagementControl" + ex.Message.ToString());
                Common.FunctionList.FunctionClass.ShowMessageBox(
                    this.errorMessbox,
                    1,
                    "提示",
                    ex.Message.ToString(),
                    Colors.Gray,
                    true,
                    Visibility.Visible,
                    Visibility.Collapsed);
                return;
            }            
        }

        /// <summary>
        /// 子窗体关闭事件时，更新DataGrid
        /// 服务实现
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of InsertAccountCompletedEventArgs</param>
        private void Client_InsertAccountCompleted(object sender, InsertAccountCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    if (e.Result.Count > 0)
                    {
                        if (this.clientList != null)
                        {
                            this.clientList.Clear();
                        }

                        // 将服务器端的LIST转换为客户端的ObservableCollection<T>
                        foreach (WCFServers.WCFAccountsRef.AccountInforBase item in e.Result)
                        {
                            if (!item.AccountID.ToString().Trim().ToUpper().Equals("ADMINISTRATOR"))
                            {
                                this.clientList.Add(new Client_AccountManagementDataList()
                                {
                                    AccountID = FunctionClass.MyIsNullOrEmpty(item.AccountID, null),

                                    // check默认值
                                    AccountIDCheck = false,
                                    AccountState = FunctionClass.MyIsNullOrEmpty(item.AccountState, null),
                                    OpName = FunctionClass.MyIsNullOrEmpty(item.OpName, null),
                                    ParentID = FunctionClass.MyIsNullOrEmpty(item.ParentID, null)
                                });
                            }
                        }

                        this.pcv = new PagedCollectionView(this.clientList);
                        this.pcv.PageSize = this.pageCount;

                        this.dgAccountManagement.ItemsSource = this.pcv;
                        this.dpDataPage.DataContext = this.pcv;

                        this.wcfLogClient.InfoAsync(((App)Application.Current).LogStr + "在帐号管理项中添加记录");
                    }
                    else
                    {
                        this.dgAccountManagement.ItemsSource = null;
                        this.dpDataPage.DataContext = null;
                        throw (new Exception("没有可显示的数据"));
                    }
                }
                else 
                {
                    throw (new Exception("InsertAccount服务返回值有错"));
                }
            }
            catch (Exception ex) 
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + "AccountManagementControl" + ex.Message.ToString());
                Common.FunctionList.FunctionClass.ShowMessageBox(
                   this.errorMessbox,
                   1,
                   "提示",
                   ex.Message.ToString(),
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }
        }
        #endregion 增加记录

        #region 删除记录

        /// <summary>
        /// 删除按钮
        /// Delete_Click
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of RoutedEventArgs</param>
        private void Delete_Click(object sender, RoutedEventArgs e)
        {
             FunctionClass.ShowMessageBox(
                    this.deleteMessbox,
                    0,
                    "提示",
                    "确定删除?",
                    Colors.Gray,
                    false,
                    Visibility.Visible,
                    Visibility.Visible);

             if (this.deleteMessbox.DialogResult == false) 
             {
                 return; 
             }            
        }

        /// <summary>
        /// 消息子窗体关闭事件
        /// 确定是否删除指定数据
        /// 是否删除指定数据的依据是：检查列表里的CHECK项是否被选中
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of EventArgs</param>
        private void DeleteMessbox_Closed(object sender, EventArgs e)
        {
            try
            {
                if (this.deleteMessbox.DialogResult == true)
                {
                  #region 将ClientList中的选中项加入参数列表ClientDataList.ParameterAccountList中

                    foreach (Client_AccountManagementDataList lst in this.clientList)
                    {
                        if (lst.AccountIDCheck)
                        {
                            bool addAccountFlag = false;

                            if (ClientDataList.ParameterAccountList.Count != 0)
                            {
                                int index = ClientDataList.ParameterAccountList.IndexOf(lst.AccountID);
                                if (index == -1)
                                {
                                    addAccountFlag = true;
                                }
                            }
                            else
                            {
                                addAccountFlag = true;
                            }

                            if (addAccountFlag)
                            {
                                ClientDataList.ParameterAccountList.Add(lst.AccountID.Trim());
                            }
                        }
                    }
                    #endregion  将ClientList中的选中项加入参数列表ClientDataList.ParameterAccountList中

                    if (ClientDataList.ParameterAccountList.Count <= 0) 
                    {
                        return;
                    }

                    this.client.DeleteAccountAsync(ClientDataList.ParameterAccountList);
                }
            }
            catch (Exception ex) 
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + "AccountManagementControl" + ex.Message.ToString());
                 FunctionClass.ShowMessageBox(
                  this.errorMessbox,
                  1,
                  "提示",
                  ex.Message.ToString(),
                  Colors.Gray,
                  true,
                  Visibility.Visible,
                  Visibility.Collapsed);

                return;
            }
        }

        /// <summary>
        /// 删除记录服务实现
        /// Client_DeleteAccountCompleted
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of DeleteAccountCompletedEventArgs</param>
        private void Client_DeleteAccountCompleted(object sender, DeleteAccountCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    if (e.Result.Count > 0)
                    {
                        // 将服务器端的LIST转换为客户端的ObservableCollection<T>
                        if (this.clientList != null)
                        {
                            this.clientList.Clear(); 
                        }

                        foreach (AccountInforBase item in e.Result)
                        {
                            if (!item.AccountID.ToString().Trim().ToUpper().Equals("ADMINISTRATOR"))
                            {
                                this.clientList.Add(new Client_AccountManagementDataList()
                                {
                                    AccountID = FunctionClass.MyIsNullOrEmpty(item.AccountID, null),

                                    // check默认值
                                    AccountIDCheck = false,
                                    AccountState = FunctionClass.MyIsNullOrEmpty(item.AccountState, null),
                                    OpName = FunctionClass.MyIsNullOrEmpty(item.OpName, null),
                                    ParentID = FunctionClass.MyIsNullOrEmpty(item.ParentID, null)
                                });
                            }
                        }

                        this.pcv = new PagedCollectionView(this.clientList);
                        this.pcv.PageSize = this.pageCount;

                        this.dgAccountManagement.DataContext = this.pcv;
                        this.dpDataPage.DataContext = this.pcv;

                        this.wcfLogClient.InfoAsync(((App)Application.Current).LogStr + "在帐号管理项中删除记录");
                    }
                    else
                    {
                        this.dgAccountManagement.DataContext = null;
                        this.dpDataPage.DataContext = null;
                        throw (new Exception("没有可显示的数据"));
                    }

                    ClientDataList.ParameterAccountList.Clear();
                }
                else
                {
                    throw (new Exception(e.Error.Message.ToString()));
                }
            }
            catch (Exception ex)
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + "AccountManagementControl" + ex.Message.ToString());
                Common.FunctionList.FunctionClass.ShowMessageBox(
                   this.errorMessbox,
                   1,
                   "提示",
                   ex.Message.ToString(),
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);

                return;
            }
        }
        #endregion  删除记录

        #region 页面载入
        /// <summary>
        /// 页面载入事件
        /// Page_Loaded
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of RoutedEventArgs</param>
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                // 调用服务端方法
                // 在页面载入时向DATAGRID中添加数据
                this.client.AccountManagementAsync();
            }
            catch (Exception ex) 
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + "AccountManagementControl" + ex.Message.ToString());
                Common.FunctionList.FunctionClass.ShowMessageBox(
                   this.errorMessbox,
                   1,
                   "提示",
                   ex.Message.ToString(),
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);

                return;      
            }
        }
        #endregion 页面载入

        #region 显示所有可登录人员信息（页面载入时)

        /// <summary>
        /// dgAccountManagement服务的实现
        /// 显示所有可登录人员信息
        /// 将服务器端的LIST转换为客户端的ObservableCollection
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of AccountManagementCompletedEventArgs</param>
        private void Client_AccountManagementCompleted(object sender, AccountManagementCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    if (e.Result.Count > 0)
                    {
                        // 将服务器端的LIST转换为客户端的ObservableCollection<T>
                        if (this.clientList != null)
                        {
                            this.clientList.Clear();
                        }

                        foreach (AccountInforBase item in e.Result)
                        {
                            if (!item.AccountID.ToString().Trim().ToUpper().Equals("ADMINISTRATOR"))
                            {
                                this.clientList.Add(new Client_AccountManagementDataList()
                                {
                                    AccountID = FunctionClass.MyIsNullOrEmpty(item.AccountID, null),

                                    // check默认值
                                    AccountIDCheck = false,
                                    AccountState = FunctionClass.MyIsNullOrEmpty(item.AccountState, null),
                                    OpName = FunctionClass.MyIsNullOrEmpty(item.OpName, null),
                                    ParentID = FunctionClass.MyIsNullOrEmpty(item.ParentID, null)
                                });
                            }
                        }

                        this.pcv = new PagedCollectionView(this.clientList);
                        this.pcv.PageSize = this.pageCount;

                        this.dgAccountManagement.DataContext = this.pcv;
                        this.dpDataPage.DataContext = this.pcv;
                    }
                    else 
                    {
                        this.dgAccountManagement.ItemsSource = null;
                        this.dpDataPage.DataContext = null;
                        throw (new Exception("没有可登录人员的数据信息")); 
                    }
                }
                else 
                {
                   throw (new Exception(e.Error.Message.ToString()));
                }
            }
            catch (Exception ex)
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + "AccountManagementControl" + ex.Message.ToString());

                Common.FunctionList.FunctionClass.ShowMessageBox(
                   this.errorMessbox,
                   1,
                   "提示",
                   ex.Message.ToString(),
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);

                return;
            }
        }

        #endregion 显示所有可登录人员信息（页面载入时)
    }
}
